package com.muse.app.service;


import com.muse.entity.CustomerArchives;
import com.muse.entity.CustomerOperation;
import com.muse.entity.Result;
import com.muse.model.CreateCustomerArchivesParam;
import com.muse.model.CustomerArchivesVo;
import com.muse.sqlutils.SqlBuilder;
import com.muse.utils.JsonUtils;
import com.muse.utils.ObjectCopy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import static com.muse.sqlutils.SqlBuilder.*;

@Service
@Slf4j
public class CustomerArchivesService {


    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Transactional(rollbackFor = Exception.class)
    public Result createCustomerArchives(CreateCustomerArchivesParam param, Integer userId) {
        CustomerArchives customerArchives = new CustomerArchives();
        customerArchives.setName(param.getName());
        customerArchives.setPhone(param.getPhone());
        customerArchives.setSex(param.getSex());
        customerArchives.setUserId(userId);
        customerArchives.setCreateTime(LocalDate.now());
        long customerId = SqlBuilder.insertReturnId("t_customer_archives", customerArchives, jdbcTemplate);
        CustomerOperation customerOperation = new CustomerOperation();
        customerOperation.setOperationProject(param.getOperationProject());
        customerOperation.setColorPlan(param.getColorPlan());
        customerOperation.setOperationTool(param.getOperationTool());
        customerOperation.setCustomerId((int) customerId);
        customerOperation.setPrice(param.getPrice());
        customerOperation.setRemark(param.getRemark());
        customerOperation.setImages(JsonUtils.toJson(param.getImages()));
        customerOperation.setCreateTime(LocalDate.now());
        SqlBuilder.insertReturnId("t_customer_operation", customerOperation, jdbcTemplate);
        return Result.success();
    }

    public Result createCustomerOperation(CreateCustomerArchivesParam param) {
        CustomerOperation customerOperation = new CustomerOperation();
        customerOperation.setOperationProject(param.getOperationProject());
        customerOperation.setColorPlan(param.getColorPlan());
        customerOperation.setOperationTool(param.getOperationTool());
        customerOperation.setCustomerId(param.getId());
        customerOperation.setPrice(param.getPrice());
        customerOperation.setRemark(param.getRemark());
        customerOperation.setImages(JsonUtils.toJson(param.getImages()));
        SqlBuilder.insertReturnId("t_customer_operation", customerOperation, jdbcTemplate);
        return Result.success();
    }

    public Result<List<CustomerArchivesVo>> list(Integer userId, Integer page, Integer pageSize) {
        List<CustomerArchivesVo> vos = new ArrayList<>();
        long total = SqlBuilder.select("t_customer_archives")
                .where(eq("user_id", userId))
                .queryForCount(jdbcTemplate);
        if (total == 0) {
            return Result.success(vos).pagination(new Result.Pagination(page, pageSize, (int) total));
        }
        List<CustomerArchives> customerArchives = SqlBuilder.select("t_customer_archives")
                .where(eq("user_id", userId))
                .order("create_time desc")
                .limit((page - 1) * pageSize, pageSize)
                .queryForList(jdbcTemplate, CustomerArchives.class);
        for (CustomerArchives customerArchive : customerArchives) {
            CustomerArchivesVo vo = new CustomerArchivesVo();
            ObjectCopy.copy(customerArchive, vo);
            String lastOperationProject = getLastOperationProject(customerArchive.getId());
            vo.setOperationProject(lastOperationProject);
            vos.add(vo);
        }
        return Result.success(vos).pagination(new Result.Pagination(page, pageSize, (int) total));
    }

    private String getLastOperationProject(int id) {
        return SqlBuilder.select("t_customer_operation")
                .selectFields("operation_project")
                .where(
                        eq("customer_id", id)
                ).order("create_time desc").limit(1).queryForScalar(jdbcTemplate, String.class);
    }

    public Result delete(Integer id) {
        SqlBuilder.delete("t_customer_archives").where(and(eq("id", id))).execute(jdbcTemplate);
        return Result.success();
    }

    public Result<List<CustomerOperation>> operationList(Integer id, Integer page, Integer pageSize) {
        List<CustomerOperation> vos = new ArrayList<>();
        long total = SqlBuilder.select("t_customer_operation")
                .where(eq("customer_id", id))
                .queryForCount(jdbcTemplate);
        if (total == 0) {
            return Result.success(vos).pagination(new Result.Pagination(page, pageSize, (int) total));
        }
        vos = SqlBuilder.select("t_customer_operation")
                .where(eq("customer_id", id))
                .order("create_time desc")
                .limit((page - 1) * pageSize, pageSize)
                .queryForList(jdbcTemplate, CustomerOperation.class);
        return Result.success(vos).pagination(new Result.Pagination(page, pageSize, (int) total));
    }
}
